package com.auto.signup.controller.weixin;

import com.auto.signup.common.model.WeixinModel;
import com.auto.signup.entity.UserInfo;
import com.auto.signup.service.IUserService;
import com.auto.signup.weixin.WebAuthScopeEnum;
import com.auto.signup.weixin.WeixinWebAuth;
import com.auto.signup.weixin.exception.AuthException;
import com.auto.signup.weixin.model.WebAuthTokenModel;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Objects;

/**
 * 微信授权相关
 * 
 * @author randyjie
 *
 */
@Controller
@RequestMapping("/weixin")
public class WeixinAuthController{

	private static final Logger logger = LoggerFactory.getLogger(WeixinAuthController.class);

	private final static String SE_WEIXIN_AUTH_KEY = "SE_WEIXIN_AUTH_KEY";
	private final static String SE_WEIXIN_AUTH_TO = "SE_WEIXIN_AUTH_TO";

	public final static String SESSION_WEIXIN_TOKEN_MODEL = "weixin-auth-tokenModel";

	@Autowired
	private WeixinWebAuth weixinWebAuth;

	@Resource
	private IUserService userService;

	@Value("${tp.weixin.auth.to}")
	private String sucTo;

	@Value("${tp.local.address}")
	private String localIP;


	@RequestMapping(value = "/callback")
	public String callback(String code, String state, HttpServletRequest request,
			HttpServletResponse response) throws AuthException {

		String token = (String) request.getSession().getAttribute(SE_WEIXIN_AUTH_KEY);
		logger.debug("winxin auth callback: {} , state:{},session auth key:{}", code, state, token);
		logger.debug("-----------========------------------seesion:{}", request.getSession().getId());
		// sucTo
		if (state.equals(token)) {
			WebAuthTokenModel tokenModel = weixinWebAuth.getAuthToken(code);
			WeixinModel weixinmodel = new WeixinModel();
			BeanUtils.copyProperties(tokenModel, weixinmodel);
			userService.checkWinxin(tokenModel);
			request.getSession().setAttribute(SESSION_WEIXIN_TOKEN_MODEL, weixinmodel);
			return autoLogin(null, request, response);
		}
		throw new RuntimeException("无效的授权登录。");
	}

	private String autoLogin(UserInfo userInfo, HttpServletRequest request, HttpServletResponse response) {

		String to = Objects.toString(request.getSession().getAttribute(SE_WEIXIN_AUTH_TO), null);
		if (to != null) {
			request.getSession().removeAttribute(SE_WEIXIN_AUTH_TO);
			return "redirect:".concat(to);
		}
		return "redirect:".concat(sucTo);
	}

	@RequestMapping(value = "/auth", method = RequestMethod.GET)
	public String auth(HttpSession session, String to) {
		String token = RandomStringUtils.randomAlphanumeric(16);
		session.setAttribute(SE_WEIXIN_AUTH_KEY, token);
		if (StringUtils.isNotBlank(to))
			session.setAttribute(SE_WEIXIN_AUTH_TO, to);
		else
			session.removeAttribute(SE_WEIXIN_AUTH_TO);
		String url = weixinWebAuth.buildAuthURL(localIP + "/weixin/callback.json",
				WebAuthScopeEnum.snsapi_base, token);
		logger.debug(url);
		return "redirect:".concat(url);
	}

	@RequestMapping(value = "/infoauth", method = RequestMethod.GET)
	public String auth2(HttpSession session, String to) {
		String token = RandomStringUtils.randomAlphanumeric(16);
		session.setAttribute(SE_WEIXIN_AUTH_KEY, token);
		if (StringUtils.isNotBlank(to))
			session.setAttribute(SE_WEIXIN_AUTH_TO, to);
		else
			session.removeAttribute(SE_WEIXIN_AUTH_TO);
		String url = weixinWebAuth.buildAuthURL(localIP + "/weixin/callback.json",
				WebAuthScopeEnum.snsapi_userinfo, token);
		logger.debug(url);
		return "redirect:".concat(url);
	}
}
